use crate::config::ActionConf;
use std::process::Command;
use crate::error::CResult;
use simple_error::*;
use  isahc::{HttpClientBuilder,http::header::USER_AGENT};
use isahc::config::{SslOption, RedirectPolicy, Configurable};
use std::time::Duration;
use std::io::{ErrorKind,Error};

fn exec_command(command:&str) -> CResult<()> {
    let r = if cfg!(target_os = "windows") {
        Command::new("cmd")
            .args(&["/C", command])
            .output()?
    } else {
        Command::new("sh")
            .arg("-c")
            .arg(command)
            .output()?
    };

    Ok(())
}

fn exec_http(haddr:&str) -> CResult<()> {
    let req = isahc::HttpClientBuilder::new()
        .timeout(Duration::from_secs(15 as u64))
        .default_header(USER_AGENT.as_str(),
                        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) \
                              AppleWebKit/537.36 (KHTML, like Gecko) \
                              Chrome/88.0.4324.150 Safari/537.36 \
                              TickChecker/1.0.0")
        .redirect_policy(RedirectPolicy::Limit(2))
        .auto_referer()
        .ssl_options(SslOption::DANGER_ACCEPT_REVOKED_CERTS)
        .build().unwrap();

    let resp = req.head(haddr)?;
    let status_code = resp.status().as_u16();
    if (status_code >= 200 && status_code <= 220) || (status_code >= 300 && status_code <= 305) {
        Ok(())
    }else {
        let custom_error = Error::new(ErrorKind::Other, format!("failed do action:{}",resp.status()));
        Err(Box::new(custom_error))
    }
}

pub fn executor_fail(data:&ActionConf) {
    match data.fail_type.as_str() {
        "http" => {
            // 执行HTTP的错误行为
            exec_http(data.target.as_str());
        }
        "command" => {
            // 执行本地命令
            exec_command(data.target.as_str());
        }
        _ => {}
    }
}

pub fn executor_recover(data:&ActionConf) {
    match data.fail_type.as_str() {
        "http" => {
            // 执行HTTP的错误行为
            exec_http(data.target.as_str());
        }
        "command" => {
            // 执行本地命令
            exec_command(data.target.as_str());
        }
        _ => {}
    }
}